package com.itfreer.print.toPdf;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

import com.itfreer.print.base.HtmlToXHtmlUtils;

/**
 * 基于poi实现doc和docx文件转换为html
 */
@Component
public class WordToHtmlImp {

	/**
	 * 将word转换为html
	 * 
	 * @param wordFile
	 *            word文件
	 * @param htmlFile
	 *            html文件
	 * @param imagePath
	 *            图片路径
	 * @throws IOException
	 */
	public void docxToHtml(InputStream wordFile, OutputStream htmlFile, String imagePath) throws IOException {
		// 1) 加载word文档生成 XWPFDocument对象
		XWPFDocument document = new XWPFDocument(wordFile);

		// 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
		File imageFolderFile = new File(imagePath);
		XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
		options.setExtractor(new FileImageExtractor(imageFolderFile));
		options.setIgnoreStylesIfUnused(false);
		options.setFragment(true);

		// 3) 将 XWPFDocument转换成XHTML
		ByteArrayOutputStream outHtmlFile = new ByteArrayOutputStream();
		XHTMLConverter.getInstance().convert(document, outHtmlFile, options);
		String htmlString = new String(outHtmlFile.toByteArray(), "UTF-8");
		outHtmlFile.close();

		String htmlContent = "";
		htmlContent += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
				+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>"
				+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + "<title></title>"
				+ "</head>" + "<body>" + htmlString + "</body>" + "</html>";

		htmlFile.write(htmlContent.getBytes());
		htmlFile.close();
	}

	/**
	 * 将word转换为html
	 * 
	 * @param wordFile
	 *            word文件
	 * @param htmlFile
	 *            html文件
	 * @param imagePath
	 *            图片路径
	 * @throws IOException
	 * @throws ParserConfigurationException
	 * @throws TransformerException
	 */
	public void docToHtml(InputStream wordFile, OutputStream htmlFile, final String imagePath)
			throws IOException, ParserConfigurationException, TransformerException {
		HWPFDocument wordDocument = new HWPFDocument(wordFile);
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		// 设置图片存放的位置
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
					float heightInches) {
				File imgPath = new File(imagePath);
				if (!imgPath.exists()) {// 图片目录不存在则创建
					imgPath.mkdirs();
				}
				File file = new File(imagePath + suggestedName);
				try {
					OutputStream os = new FileOutputStream(file);
					os.write(content);
					os.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return imagePath + suggestedName;
			}
		});

		// 解析word文档
		wordToHtmlConverter.processDocument(wordDocument);
		Document htmlDocument = wordToHtmlConverter.getDocument();
		DOMSource domSource = new DOMSource(htmlDocument);
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer serializer = factory.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");

		ByteArrayOutputStream htmlOut = new ByteArrayOutputStream();
		StreamResult streamResult = new StreamResult(htmlOut);
		serializer.transform(domSource, streamResult);
		htmlOut.close();
		String html = new String(htmlOut.toByteArray(), "utf-8");
		// 默认不能识别文档中的字体，只得转换为yahei
		html = html.replace("Times New Roman", "Microsoft YaHei");
		html = HtmlToXHtmlUtils.toXHtml(html);
		
		htmlFile.write(html.getBytes());
		htmlFile.close();
	}
}